package com.beg.cant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.beg.cant.comment.utils.WechatSecurityHelper;
import com.beg.cant.dto.PageRequest;
import com.beg.cant.dto.PageResponse;
import com.beg.cant.entity.Order;
import com.beg.cant.entity.Post;
import com.beg.cant.entity.User;
import com.beg.cant.mapper.OrderMapper;
import com.beg.cant.mapper.PostMapper;
import com.beg.cant.mapper.UserMapper;
import com.beg.cant.service.PostService;
import com.beg.cant.vo.PostVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService {
    private final PostMapper postMapper;
    private final UserMapper userMapper;
    private final OrderMapper orderMapper;
    @Autowired
    private WechatSecurityHelper wechatSecurityHelper;
    @Override
    public PostVO getPostsById(Long id) {
        Post post = postMapper.selectById(id);
        return getUserById(post);
    }

    @Override
    public PageResponse<PostVO> getPostslist(PageRequest pageRequest) {
        // 创建分页对象
        Page<Post> page = new Page<>(pageRequest.getPageNum(), pageRequest.getPageSize());
        LambdaQueryWrapper<Post> postWrapper = new LambdaQueryWrapper<>();
        
        // 添加时间范围筛选
        if (pageRequest.getStartTime() != null) {
            postWrapper.ge(Post::getCreatedAt, pageRequest.getStartTime());
        }
        if (pageRequest.getEndTime() != null) {
            postWrapper.le(Post::getCreatedAt, pageRequest.getEndTime());
        }
        // 添加code筛选
        if (pageRequest.getCode()!=null){
            postWrapper.eq(Post::getUserId,pageRequest.getCode());
        }
        
        postWrapper.orderByAsc(Post::getCreatedAt);
        // 执行分页查询
        IPage<Post> postPage = postMapper.selectPage(page, postWrapper);
        
        // 转换为VO对象
        List<PostVO> postVOS = postPage.getRecords().stream()
                .map(item -> {
                    // 创建LambdaQueryWrapper并设置查询条件
                    LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(Order::getPostsId, item.getId());
                    User user = userMapper.selectById(item.getUserId());
                    PostVO postVO = PostVO.builder()
                            .userName(user.getName())
                            .avatar(user.getImage())
                            .amount(orderMapper.selectList(wrapper).stream()
                                    .map(Order::getAmount)
                                    .reduce(0.0, Double::sum))
                            .build();
                    BeanUtils.copyProperties(item,postVO);
                    return postVO;
                })
                .collect(Collectors.toList());
        // 构建分页响应
        return PageResponse.of(postVOS, postPage.getTotal(), pageRequest);
    }

    @Override
    public List<PostVO> getUserPostsById(Long id) {
        // 1. 获取原始帖子列表
        List<Post> posts = postMapper.selectList(
                new LambdaQueryWrapper<Post>().eq(Post::getUserId, id)
        );
        if (CollectionUtils.isEmpty(posts)) {
            return Collections.emptyList(); // 提前返回空列表
        }
        // 2. 批量提取帖子ID集合
        List<Long> postIds = posts.stream()
                .map(Post::getId)
                .collect(Collectors.toList());

        // 3. 批量查询订单数据并按postId分组求和
        Map<Long, Double> amountSumMap = orderMapper.selectList(
                        new LambdaQueryWrapper<Order>().in(Order::getPostsId, postIds).eq(Order::getStatus,1)
                ).stream()
                .collect(Collectors.groupingBy(
                        Order::getPostsId,
                        Collectors.summingDouble(Order::getFee)
                ));

        // 4. 构建VO并赋值
        return posts.stream()
                .map(post -> {
                    PostVO postVO = PostVO.builder().build();
                    BeanUtils.copyProperties(post, postVO);
                    postVO.setAmount(amountSumMap.getOrDefault(post.getId(), 0.0));
                    return postVO;
                })
                .collect(Collectors.toList());
    }

    @Override
    public void savePostsById(Post post) throws IOException {
//        User user = userMapper.selectById(post.getUserId());
        wechatSecurityHelper.checkContent(post.getContent(),null);
        post.setCreatedAt(LocalDateTime.now());
        postMapper.insert(post);
    }

    public PostVO getUserById(Post post) {
        User user = userMapper.selectById(post.getUserId());
        PostVO postVO = PostVO.builder().build();
        BeanUtils.copyProperties(post,postVO);
        postVO.setAvatar(user.getImage());
        postVO.setUserName(user.getName());
        return postVO;
    }
}
